<template>
<div>
    <div class="container">
		
		<el-form :inline="true"  class="demo-form-inline">
		  <el-form-item label="组名">
		    <el-input v-model="groupid" placeholder="按管理员分配的填写" type="password"></el-input>
		  </el-form-item>
		  <el-form-item label="键名">
			  <el-input v-model="appid" placeholder="按管理员分配的填写" type="password"></el-input>
		  </el-form-item>
		  <el-form-item>
		    <el-button type="primary" @click="onSubmit">查询</el-button>
		  </el-form-item>
		</el-form>
		
		<div id="addFile" class="fl">上传文件</div>

		<div v-for="(item, index) in upList" :key="index">
			<p>{{item.fileName}} - 正在上传...</p>
			<el-progress :text-inside="true" :stroke-width="26" :percentage="item.progress"></el-progress>
		</div>

		<el-divider></el-divider>
		<div v-show="ispass">所有共享文件：</div>
        <el-table
                :data="shareList"
                style="width: 100%"
				v-show="ispass">
            <el-table-column
                    prop="fileName"
                    label="文件名称"
                    align="center"
                    width="180">
            </el-table-column>
            <el-table-column
                    prop="fileSize"
                    align="center"
                    label="文件大小">
            </el-table-column>
            <el-table-column
                    prop="uploader"
                    align="center"
                    label="上传者">
            </el-table-column>
			<el-table-column
			        prop="createdTime"
			        align="center"
			        label="上传时间">
			</el-table-column>
            <el-table-column label="操作" width="200" align="center"  fixed="right">
                <template slot-scope="scope">
					<el-button
					        type="text"
					        icon="el-icon-download"
					        class="red"
					        @click="download(scope.row)"
					>下载</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
</div>
</template>
<script>
// import $ from 'jquery'
// import WebUploader from 'webuploader'
module.exports = {
    name: 'webupload',
    props:{
        headers:{
            type: String,
            default:''
        },
        filenumlimit:{
            type:Number,
            default:undefined
        },
        filesizelimit:{
            type:Number,
            default:undefined
        },
        chunksize:{
            type: Number,
            default: 5*1024*1024
        },
        user:{
            type:String,
            default: ''
        },
  //       groupid:{
  //           type:String,
  //           default: ''
  //       },
		// appid:{
		//     type:String,
		//     default: ''
		// }
    },
    data() {
        return {
            uploader:{},
			upList:[],//上传文件集合
            shareList:[],//共享文件集合
			ispass:false,
			groupid:'',
			appid:''
        }
    },
    mounted() {
		this.ispass = false;
		this.uploader = $.uploaderInit({
			// server: 'http://localhost:9555' + '/api/file/breakpoint-upload',
			server: window.location.origin + '/api/file/breakpoint-upload',
			pick: {
				id: '#addFile',
				multiple: true
			},
			chunked: true,
			chunkSize: this.chunksize,
			fileNumLimit: this.filenumlimit,
			fileSizeLimit: this.filesizelimit,
			fileQueued: (file) => {
				if(!this.ispass) {
					alert("先填写内容进行验证！")
					//return;
				}
				this.upList.push(
				{
					fileId:file.id,
					fileName: file.name.length > 20 ? (file.name.substring(0,20) + '...'): file.name,
					fileSize: file.size,
					progress: 0,
				})
				// 上传文件
				this.uploader.upload(file);
			},
			// 上传文件之前先计算文件的MD5和ID
			uploadBeforeSend: (object, data, headers) => {
				let file = object.file;
				data.md5 = file.md5 || '';
				data.uid = file.uid;
			},
			// 上传进度更新
			uploadProgress: (file, percentage) => {
				let pro = Math.round(percentage * 100);
				this.upList.find(x => x.fileId == file.id).progress = pro;
			},
			// 上传完成后执行
			uploadSuccess: (file, response) => {
				if(response && response.success){
					this.fileAdd(file);
				}
				//上传目录移除
				this.upList.splice(this.upList.findIndex(x => x.fileId == file.id), 1);
                
			},
			// 上传出错时执行
			uploadError: (file, reason) => {
				alert(file.name + "上传出错: " + reason);
				//上传目录移除
				this.upList.splice(this.upList.findIndex(x => x.fileId == file.id), 1);
			},
			beforeInit: () => {
				var that = this;
				// 这个必须要写在实例化前面
				WebUploader.Uploader.register({
					'before-send-file': 'beforeSendFile',
					'before-send': 'beforeSend'
				}, {
					// 时间点1：所有分块进行上传之前调用此函数
					beforeSendFile: function(file) {
						let deferred = WebUploader.Deferred();
						(new WebUploader.Uploader()).md5File(file, 0, 5242880).progress(function(percentage) {
							// 显示计算进度
						}).then(function(val) {
							file.md5 = val;
							file.uid = WebUploader.Base.guid();
							// 进行md5判断
							$.ajax({
								url: window.location.origin + '/api/file/check-file',
								type: 'GET',
								showError: false,
								global: false,
								data: {
									fileName: file.name,
									md5: file.md5
								},
								success: (data) => {
									let status = data.errorCode;
									deferred.resolve();
									switch (status) {
										case 0:
											// 忽略上传过程，直接标识上传成功；
											that.uploader.skipFile(file);
											file.pass = true;
											//文件存在，直接添加
											that.fileAdd(file);
											break;
										case 16:
											// 部分已经上传到服务器了，但是差几个模块。
											file.missChunks = data.data;
											break;
										default:
											break;
									}
								}
							})
						})
						return deferred.promise();
					},
					// 时间点2：如果有分块上传，则每个分块上传之前调用此函数
					beforeSend: function(block) {
						let deferred = WebUploader.Deferred();
						// 当前未上传分块
						let missChunks = block.file.missChunks;
						// 当前分块
						let blockChunk = block.chunk;
						if (missChunks !== null && missChunks !== undefined && missChunks !== '') {
							let flag = true;
							for (let i = 0; i < missChunks.length; i++) {
								if (blockChunk === parseInt(missChunks[i])) {
									// 存在还未上传的分块
									flag = false;
									break;
								}
							}
							if (flag) {
								deferred.reject();
							} else {
								deferred.resolve();
							}
						} else {
							deferred.resolve();
						}
						return deferred.promise();
					}
				});
			}
		});
		
		this.getFileList();
    },
    methods: {
		onSubmit(){
			this.ispass = this.getFileList();
		},
		fileAdd(file) {
			var that = this;
			$.ajax({
				type: "post",
				url: window.location.origin + '/api/file/add',
				async: true,
				contentType: "application/json; charset=utf-8",
				data: JSON.stringify({
					fileName: file.name,
					fileMd5: file.md5,
					suffix: file.ext,
					fileSize: file.size,
					uploader: that.user,
					appId: that.appid,
					groupId: that.groupid,
				}),
				success: function(res) {
					if (res.success) {
						that.getFileList();
					}
				}
			});		
		},
		getFileList() {
			var that = this;
			$.ajax({
				type: "get",
				url: window.location.origin + '/api/file/list',
				async: true,
				data: {
					pageNo: 1,
					pageSize: 999,
					appId: that.appid,
					groupId: that.groupid
				},
				success: function(res) {
					if (res.success) {
						that.shareList = [];
						for (let file of res.data) {
							that.shareList.push(
							{
								fileId:file.id,
								fileName: file.fileName.length > 30 ? (file.fileName.substring(0,30) + '...'): file.fileName,
								fileSize: Math.ceil(file.fileSize/1000) + ' KB',
								uploader: file.uploader,
								createdTime: that.formatDate(file.createdTime)
							})
						}
						that.ispass = true;
					}
				}
			});
		},
		//时间戳转换方法    date:时间戳数字
		formatDate(date) {
		  var date = new Date(date);
		  var YY = date.getFullYear() + '-';
		  var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
		  var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
		  var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
		  var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
		  var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
		  return YY + MM + DD +" "+hh + mm + ss;
		},
		download(row){
			var that = this;
			//加了isSource为采用原名称
			window.open(window.location.origin +"/api/file/download/" + row.fileId + "?isSource=" + true);		
		}
    }
}
</script>
<style>
    .container {
		width: 100vw;
        background: #fff;
    }
</style>
